package org.jeecg.modules.flow.callback.delivery.task;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.business.delivery.entity.WmsDeliveryTask;
import org.jeecg.modules.business.delivery.entity.vo.WmsDeliveryTaskVO;
import org.jeecg.modules.business.delivery.service.IWmsDeliveryTaskService;
import org.jeecg.modules.business.outbound.entity.WmsOutReceiptTask;
import org.jeecg.modules.business.outbound.entity.vo.OutBoundTaskSaveVO;
import org.jeecg.modules.business.outbound.service.IWmsOutReceiptTaskService;
import org.jeecg.modules.flow.sys.common.BaseCustomBeanRun;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * 调拨任务保存 回调bean
 *
 * @author gongwenkai
 * @version 1.0.0
 * @since 2023-09-26
 */
@RequiredArgsConstructor
@Component
public class DeliveryTaskSaveBean<T> extends BaseCustomBeanRun<T> {

    private final IWmsDeliveryTaskService deliveryTaskService;

    /**
     * 业务逻辑 调拨任务保存
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void actureRun() {
        BaseFlowDto baseFlowDto = this.getBaseFlowDto();
        // 获取请求参数
        baseFlowDto.translateClass(WmsDeliveryTaskVO.class);
        WmsDeliveryTaskVO deliveryTaskVO= (WmsDeliveryTaskVO)baseFlowDto.getData();
        String taskId;
        if(StrUtil.isEmpty(deliveryTaskVO.getId())){
            WmsDeliveryTask wmsDeliveryTask = BeanUtil.toBean(deliveryTaskVO, WmsDeliveryTask.class);
            //保存出库任务
            taskId = deliveryTaskService.saveMain(wmsDeliveryTask, deliveryTaskVO.getWmsDeliveryTaskMaterialList());
        }else{
            taskId=deliveryTaskVO.getId();
            WmsDeliveryTask dbWmsDeliveryTask = deliveryTaskService.getById(taskId);
            if (Objects.isNull(dbWmsDeliveryTask)) {
                throw new JeecgBootException("未找到对应数据");
            }
            WmsDeliveryTask wmsDeliveryTask = BeanUtil.toBean(deliveryTaskVO, WmsDeliveryTask.class);
            deliveryTaskService.updateMain(wmsDeliveryTask, deliveryTaskVO.getWmsDeliveryTaskMaterialList());
        }
        // 当前前端调用业务需要你返回的
        baseFlowDto.setResult(Result.OK());
        // id是保存业务记录的id。用于生成业务流程信息记录
        baseFlowDto.setInfoId(taskId);
    }
}
